//
//  BMSLifecycleManager.m
//  WDBMS
//
//  Created by YeJary on 2025/5/13.
//

#import "BMSLifecycleManager.h"
#import "BMSPermissionManager.h"
#import "BMSDeviceInfo.h"
#import "BMSPrivate.h"

@interface BMSLifecycleManager ()

@property (nonatomic, assign) BOOL isAppActive;
@property (nonatomic, assign) BOOL hasEnteredForeground;
@end

@implementation BMSLifecycleManager

+ (instancetype)shared {
    static BMSLifecycleManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)startMonitoring {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidBecomeActive)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidEnterBackground)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
}

- (void)WDApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    if ([BMSLifecycleManager isFirstLaunchByInstallDate]) {
        [BMSOpMergeEventBuilder event_userOpWithAct:BMS_EVENT_USER_LOGIN description:BMS_WDS_FIRST_LAUNCH_AFTER_INSTALL];
        
    }
}

- (void)appDidBecomeActive {
    self.isAppActive = YES;
    if (!self.hasEnteredForeground) {
        self.hasEnteredForeground = YES;
    }
    if (self.onDidBecomeActive) {
        self.onDidBecomeActive();
    }

    [[BMSPermissionManager sharedManager] fetchIdentifiersWithCompletion:^(NSString * _Nullable idfa, NSString *idfv) {
        [[BMSDeviceInfo shared] updateWithIDFA:idfa idfv:idfv];
    }];
}

- (void)appDidEnterBackground {
    self.isAppActive = NO;
    if (self.onDidEnterBackground) {
        self.onDidEnterBackground();
    }
}

+ (BOOL)isFirstLaunchByInstallDate {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
    NSDate *installDate = attr[NSFileCreationDate];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDate *savedInstallDate = [defaults objectForKey:@"kInstallDate"];
    if (!savedInstallDate || ![savedInstallDate isEqualToDate:installDate]) {
        [defaults setObject:installDate forKey:@"kInstallDate"];
        [defaults synchronize];
        return YES;
    }
    return NO;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
